<?php
$page_title = '编排监考员 - 考务管理系统';
require 'common/header.php';
checkLogin();
requireRole($conn, '考试项目管理员');

// 获取考试项目ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    header('Location: exam_projects.php');
    exit();
}

// 获取考试项目信息
$exam_sql = "SELECT * FROM exams WHERE id = ?";
$exam_stmt = $conn->prepare($exam_sql);
$exam_stmt->bind_param('i', $exam_id);
$exam_stmt->execute();
$exam_result = $exam_stmt->get_result();

if ($exam_result->num_rows === 0) {
    header('Location: exam_projects.php');
    exit();
}

$exam = $exam_result->fetch_assoc();

// 处理监考员编排请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_invigilators'])) {
    try {
        $conn->begin_transaction();

        // 获取所有在职员工信息
        $staff_data = getAllActiveStaff($conn);

        // 获取监考意愿信息
        $intentions_data = getSignupIntentions($conn, $exam_id);

        // 获取现有编排信息
        $arrangements = getExamArrangements($conn, $exam_id);

        // 执行智能监考员分配
        $assignment_results = assignInvigilatorsIntelligently($staff_data, $intentions_data, $arrangements);

        // 更新数据库中的编排信息
        foreach ($assignment_results as $session_number => $session_assignments) {
            $update_sql = "UPDATE arrange_examination_rooms_and_invigilators
                          SET room_assignments = ?
                          WHERE exam_id = ? AND session_number = ?";
            $update_stmt = $conn->prepare($update_sql);
            $assignments_json = json_encode($session_assignments, JSON_UNESCAPED_UNICODE);
            $update_stmt->bind_param('sii', $assignments_json, $exam_id, $session_number);
            $update_stmt->execute();
        }

        // 更新考试项目进度为4
        $progress_sql = "UPDATE exams SET project_progress = 4 WHERE id = ?";
        $progress_stmt = $conn->prepare($progress_sql);
        $progress_stmt->bind_param('i', $exam_id);
        $progress_stmt->execute();

        $conn->commit();
        $success_message = "监考员编排完成！项目已进入最终阶段";

        // 刷新考试项目信息
        $exam_stmt->execute();
        $exam_result = $exam_stmt->get_result();
        $exam = $exam_result->fetch_assoc();

    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "编排失败: " . $e->getMessage();
    }
}

// 获取所有在职员工
function getAllActiveStaff($conn) {
    $sql = "SELECT * FROM staff WHERE serving = TRUE ORDER BY service_years DESC, responsibility DESC, risk_index ASC";
    $result = $conn->query($sql);
    $staff = [];

    while ($row = $result->fetch_assoc()) {
        $staff[$row['user_id']] = $row;
    }

    return $staff;
}

// 获取监考意愿信息
function getSignupIntentions($conn, $exam_id) {
    $sql = "SELECT * FROM signups_leaves WHERE exam_id = ? ORDER BY signup_time ASC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $intentions = [];
    while ($row = $result->fetch_assoc()) {
        $intentions[$row['user_id']] = $row;
    }

    return $intentions;
}

// 获取考试编排信息
function getExamArrangements($conn, $exam_id) {
    $sql = "SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $arrangements = [];
    while ($row = $result->fetch_assoc()) {
        $arrangements[$row['session_number']] = $row;
    }

    return $arrangements;
}

// 智能监考员分配算法
function assignInvigilatorsIntelligently($staff_data, $intentions_data, $arrangements) {
    $assignment_results = [];
    $global_assigned = []; // 全局已分配监考员记录

    foreach ($arrangements as $session_number => $arrangement) {
        $room_assignments = json_decode($arrangement['room_assignments'], true);
        $session_assigned = []; // 本场次已分配监考员

        // 为每个考场分配监考员
        foreach ($room_assignments as &$room) {
            $required_count = count($room['invigilators']);
            $assigned_invigilators = [];

            // 获取候选监考员列表（按优先级排序）
            $candidates = getCandidateInvigilators($staff_data, $intentions_data, $global_assigned, $session_assigned);

            // 分配监考员
            $assigned_invigilators = assignToRoom($candidates, $required_count, $session_assigned);

            // 更新分配记录
            foreach ($assigned_invigilators as $invigilator) {
                $session_assigned[] = $invigilator['user_id'];
                $global_assigned[] = $invigilator['user_id'];
            }

            // 更新考场的监考员信息
            $room['assigned_invigilators'] = $assigned_invigilators;
            $room['invigilators'] = array_map(function($inv) {
                return $inv['name'];
            }, $assigned_invigilators);
        }

        $assignment_results[$session_number] = $room_assignments;
    }

    return $assignment_results;
}

// 获取候选监考员（按优先级排序）
function getCandidateInvigilators($staff_data, $intentions_data, $global_assigned, $session_assigned) {
    $candidates = [];

    foreach ($staff_data as $user_id => $staff) {
        // 跳过已分配的监考员
        if (in_array($user_id, $global_assigned) || in_array($user_id, $session_assigned)) {
            continue;
        }

        $priority_score = calculatePriorityScore($staff, $intentions_data[$user_id] ?? null);

        $candidates[] = [
            'user_id' => $user_id,
            'name' => $staff['name'],
            'gender' => $staff['gender'],
            'service_years' => $staff['service_years'],
            'responsibility' => $staff['responsibility'],
            'risk_index' => $staff['risk_index'],
            'priority_score' => $priority_score,
            'intention' => $intentions_data[$user_id]['signup_intention'] ?? null,
            'signup_time' => $intentions_data[$user_id]['signup_time'] ?? null
        ];
    }

    // 按优先级分数排序
    usort($candidates, function($a, $b) {
        return $b['priority_score'] <=> $a['priority_score'];
    });

    return $candidates;
}

// 计算优先级分数
function calculatePriorityScore($staff, $intention) {
    $score = 0;

    // 意愿优先原则 (40分)
    if ($intention) {
        if ($intention['signup_intention'] == 1) {
            $score += 40; // 希望参加
        } elseif ($intention['signup_intention'] == 0) {
            $score += 10; // 拒绝参加
        }
    } else {
        $score += 25; // 未填报
    }

    // 责任心等级 (20分)
    $score += ($staff['responsibility'] / 10) * 20;

    // 工作年限 (15分)
    $score += min($staff['service_years'] / 10, 1) * 15;

    // 风险指数 (15分，越低越好)
    $score += (2 - min($staff['risk_index'], 2)) / 2 * 15;

    // 早报名原则 (10分)
    if ($intention && $intention['signup_time']) {
        $days_ago = (time() - strtotime($intention['signup_time'])) / (24 * 3600);
        $score += min($days_ago / 7, 1) * 10;
    }

    return $score;
}

// 为考场分配监考员
function assignToRoom($candidates, $required_count, &$session_assigned) {
    $assigned = [];
    $gender_balance = ['男' => 0, '女' => 0];
    $experience_balance = ['senior' => 0, 'junior' => 0];

    for ($i = 0; $i < $required_count && $i < count($candidates); $i++) {
        $best_candidate = null;
        $best_index = -1;
        $best_balance_score = -1;

        foreach ($candidates as $index => $candidate) {
            if (in_array($candidate['user_id'], $session_assigned)) {
                continue;
            }

            // 计算平衡分数
            $balance_score = calculateBalanceScore($candidate, $gender_balance, $experience_balance, $required_count);

            if ($balance_score > $best_balance_score) {
                $best_balance_score = $balance_score;
                $best_candidate = $candidate;
                $best_index = $index;
            }
        }

        if ($best_candidate) {
            $assigned[] = $best_candidate;
            $session_assigned[] = $best_candidate['user_id'];

            // 更新平衡统计
            $gender_balance[$best_candidate['gender']]++;
            if ($best_candidate['service_years'] >= 3) {
                $experience_balance['senior']++;
            } else {
                $experience_balance['junior']++;
            }

            // 从候选列表中移除
            unset($candidates[$best_index]);
            $candidates = array_values($candidates);
        }
    }

    return $assigned;
}

// 计算平衡分数
function calculateBalanceScore($candidate, $gender_balance, $experience_balance, $required_count) {
    $score = $candidate['priority_score'];

    // 性别平衡加分
    if ($required_count >= 2) {
        $gender_diff = abs($gender_balance['男'] - $gender_balance['女']);
        if ($gender_diff > 0) {
            $minority_gender = $gender_balance['男'] < $gender_balance['女'] ? '男' : '女';
            if ($candidate['gender'] === $minority_gender) {
                $score += 20; // 性别平衡加分
            }
        }
    }

    // 经验平衡加分
    if ($required_count >= 2) {
        $exp_diff = abs($experience_balance['senior'] - $experience_balance['junior']);
        if ($exp_diff > 0) {
            $is_senior = $candidate['service_years'] >= 3;
            $minority_exp = $experience_balance['senior'] < $experience_balance['junior'] ? 'senior' : 'junior';

            if (($is_senior && $minority_exp === 'senior') || (!$is_senior && $minority_exp === 'junior')) {
                $score += 15; // 经验平衡加分
            }
        }
    }

    return $score;
}

// 获取当前编排结果
$current_arrangements = getExamArrangements($conn, $exam_id);
$staff_list = getAllActiveStaff($conn);
$intentions_list = getSignupIntentions($conn, $exam_id);
?>

<div class="page-header">
    <h1 class="page-title">编排监考员</h1>
    <p class="page-description">为考试项目"<?php echo htmlspecialchars($exam['exam_name']); ?>"进行智能监考员编排</p>
</div>

<?php if (isset($success_message)): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success_message); ?>
    </div>
<?php elseif (isset($error_message)): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error_message); ?>
    </div>
<?php endif; ?>

<!-- 项目信息 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">考试项目信息</h3>
        <div class="project-status">
            <span class="status-badge status-<?php echo $exam['project_progress']; ?>">
                阶段 <?php echo $exam['project_progress']; ?>/4
            </span>
        </div>
    </div>
    <div class="card-content">
        <div class="project-info-grid">
            <div class="info-item">
                <label>项目名称：</label>
                <span><?php echo htmlspecialchars($exam['exam_name']); ?></span>
            </div>
            <div class="info-item">
                <label>计划时间：</label>
                <span><?php echo $exam['planned_start_date'] . ' 至 ' . $exam['planned_end_date']; ?></span>
            </div>
            <div class="info-item">
                <label>需要监考员：</label>
                <span><?php echo $exam['required_invigilators'] ?: '未计算'; ?>人</span>
            </div>
            <div class="info-item">
                <label>在职员工总数：</label>
                <span><?php echo count($staff_list); ?>人</span>
            </div>
        </div>
    </div>
</div>

<!-- 监考员选用原则说明 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">监考员选用原则</h3>
    </div>
    <div class="card-content">
        <div class="principles-grid">
            <div class="principle-item">
                <div class="principle-icon">🎯</div>
                <div class="principle-content">
                    <h4>意愿优先原则</h4>
                    <p>希望参加 > 未填报 > 拒绝参加</p>
                </div>
            </div>
            <div class="principle-item">
                <div class="principle-icon">⚖️</div>
                <div class="principle-content">
                    <h4>性别平衡原则</h4>
                    <p>每个考场尽量男女搭配</p>
                </div>
            </div>
            <div class="principle-item">
                <div class="principle-icon">👥</div>
                <div class="principle-content">
                    <h4>新老搭配原则</h4>
                    <p>资深监考员与新手监考员搭配</p>
                </div>
            </div>
            <div class="principle-item">
                <div class="principle-icon">🛡️</div>
                <div class="principle-content">
                    <h4>风险规避原则</h4>
                    <p>避免高风险指数监考员</p>
                </div>
            </div>
            <div class="principle-item">
                <div class="principle-icon">⏰</div>
                <div class="principle-content">
                    <h4>早报名早安排</h4>
                    <p>按报名时间优先安排</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 当前编排结果 -->
<?php if (!empty($current_arrangements)): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title">当前编排结果</h3>
        <div class="action-buttons">
            <form method="post" style="display: inline;">
                <button type="submit" name="assign_invigilators" class="btn btn-primary"
                        onclick="return confirm('确定要重新编排监考员吗？这将替换现有的编排结果。')">
                    编排该项目的监考员
                </button>
            </form>
            <a href="violations_display.php" class="btn btn-secondary">展示违规记录</a>
        </div>
    </div>

    <div class="card-content">
        <?php foreach ($current_arrangements as $session_number => $arrangement): ?>
            <div class="session-section">
                <h4>第<?php echo $session_number; ?>场考试</h4>
                <div class="session-info">
                    <p><strong>时间：</strong><?php echo $arrangement['exam_date'] . ' ' . $arrangement['start_time'] . '-' . $arrangement['end_time']; ?></p>
                    <p><strong>考场类型：</strong><?php echo $arrangement['room_type']; ?></p>
                </div>

                <?php
                $room_assignments = json_decode($arrangement['room_assignments'], true);
                if ($room_assignments):
                ?>
                <div class="assignments-table-container">
                    <table class="assignments-table">
                        <thead>
                            <tr>
                                <th>课室号</th>
                                <th>考场号</th>
                                <th>监考员</th>
                                <th>性别搭配</th>
                                <th>经验搭配</th>
                                <th>风险评估</th>
                                <th>意愿状态</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($room_assignments as $assignment): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($assignment['room_number']); ?></td>
                                    <td><?php echo htmlspecialchars($assignment['exam_room_number']); ?></td>
                                    <td>
                                        <div class="invigilators-list">
                                            <?php foreach ($assignment['invigilators'] as $invigilator): ?>
                                                <span class="invigilator-name"><?php echo htmlspecialchars($invigilator); ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php
                                        // 分析性别搭配
                                        $genders = [];
                                        if (isset($assignment['assigned_invigilators'])) {
                                            foreach ($assignment['assigned_invigilators'] as $inv) {
                                                $genders[] = $inv['gender'];
                                            }
                                        }
                                        $gender_balance = analyzeGenderBalance($genders);
                                        echo $gender_balance;
                                        ?>
                                    </td>
                                    <td>
                                        <?php
                                        // 分析经验搭配
                                        $experiences = [];
                                        if (isset($assignment['assigned_invigilators'])) {
                                            foreach ($assignment['assigned_invigilators'] as $inv) {
                                                $experiences[] = $inv['service_years'];
                                            }
                                        }
                                        $exp_balance = analyzeExperienceBalance($experiences);
                                        echo $exp_balance;
                                        ?>
                                    </td>
                                    <td>
                                        <?php
                                        // 分析风险评估
                                        $risks = [];
                                        if (isset($assignment['assigned_invigilators'])) {
                                            foreach ($assignment['assigned_invigilators'] as $inv) {
                                                $risks[] = $inv['risk_index'];
                                            }
                                        }
                                        $risk_assessment = analyzeRiskAssessment($risks);
                                        echo $risk_assessment;
                                        ?>
                                    </td>
                                    <td>
                                        <?php
                                        // 分析意愿状态
                                        $intentions = [];
                                        if (isset($assignment['assigned_invigilators'])) {
                                            foreach ($assignment['assigned_invigilators'] as $inv) {
                                                $intention = $intentions_list[$inv['user_id']] ?? null;
                                                $intentions[] = $intention ? $intention['signup_intention'] : null;
                                            }
                                        }
                                        $intention_status = analyzeIntentionStatus($intentions);
                                        echo $intention_status;
                                        ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
</div>
<?php else: ?>
<div class="card">
    <div class="card-content">
        <div class="empty-state">
            <div class="empty-icon">👥</div>
            <h3>暂无编排信息</h3>
            <p>请先完成考场编排和预编排监考员工作</p>
            <a href="arrange_rooms_invigilators.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">返回考场编排</a>
        </div>
    </div>
</div>
<?php endif; ?>

<?php
// 分析函数
function analyzeGenderBalance($genders) {
    if (empty($genders)) return '<span class="status-unknown">未知</span>';

    $male_count = count(array_filter($genders, function($g) { return $g === '男'; }));
    $female_count = count(array_filter($genders, function($g) { return $g === '女'; }));

    if ($male_count > 0 && $female_count > 0) {
        return '<span class="status-good">✓ 男女搭配</span>';
    } elseif (count($genders) == 1) {
        return '<span class="status-neutral">单人监考</span>';
    } else {
        return '<span class="status-warning">同性监考</span>';
    }
}

function analyzeExperienceBalance($experiences) {
    if (empty($experiences)) return '<span class="status-unknown">未知</span>';

    $senior_count = count(array_filter($experiences, function($e) { return $e >= 3; }));
    $junior_count = count($experiences) - $senior_count;

    if ($senior_count > 0 && $junior_count > 0) {
        return '<span class="status-good">✓ 新老搭配</span>';
    } elseif (count($experiences) == 1) {
        return '<span class="status-neutral">单人监考</span>';
    } elseif ($senior_count > 0) {
        return '<span class="status-neutral">资深监考</span>';
    } else {
        return '<span class="status-warning">新手监考</span>';
    }
}

function analyzeRiskAssessment($risks) {
    if (empty($risks)) return '<span class="status-unknown">未知</span>';

    $max_risk = max($risks);
    $avg_risk = array_sum($risks) / count($risks);

    if ($max_risk <= 1.2) {
        return '<span class="status-good">✓ 低风险</span>';
    } elseif ($avg_risk <= 1.5) {
        return '<span class="status-neutral">中等风险</span>';
    } else {
        return '<span class="status-warning">高风险</span>';
    }
}

function analyzeIntentionStatus($intentions) {
    if (empty($intentions)) return '<span class="status-unknown">未知</span>';

    $accept_count = count(array_filter($intentions, function($i) { return $i === 1; }));
    $reject_count = count(array_filter($intentions, function($i) { return $i === 0; }));
    $null_count = count(array_filter($intentions, function($i) { return $i === null; }));

    if ($accept_count == count($intentions)) {
        return '<span class="status-good">✓ 全部希望参加</span>';
    } elseif ($accept_count > 0) {
        return '<span class="status-neutral">部分希望参加</span>';
    } elseif ($null_count > 0) {
        return '<span class="status-neutral">未填报意愿</span>';
    } else {
        return '<span class="status-warning">拒绝参加</span>';
    }
}
?>

<style>
/* 监考员编排页面样式 */
.project-info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.info-item {
    display: flex;
    align-items: center;
}

.info-item label {
    font-weight: 600;
    margin-right: 10px;
    min-width: 100px;
}

.status-badge {
    padding: 5px 15px;
    border-radius: 15px;
    font-size: 14px;
    font-weight: 500;
    background-color: var(--primary-blue);
    color: white;
}

.principles-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
}

.principle-item {
    display: flex;
    align-items: flex-start;
    gap: 15px;
    padding: 15px;
    background: var(--background-light);
    border-radius: 8px;
    border-left: 4px solid var(--primary-blue);
}

.principle-icon {
    font-size: 24px;
    flex-shrink: 0;
}

.principle-content h4 {
    margin: 0 0 5px 0;
    color: var(--text-primary);
    font-size: 14px;
}

.principle-content p {
    margin: 0;
    color: var(--text-secondary);
    font-size: 12px;
}

.session-section {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
}

.session-section h4 {
    color: var(--primary-blue);
    margin-bottom: 10px;
}

.session-info {
    margin-bottom: 15px;
    font-size: 14px;
}

.assignments-table-container {
    overflow-x: auto;
}

.assignments-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.assignments-table th,
.assignments-table td {
    padding: 8px;
    text-align: left;
    border: 1px solid var(--border-color);
}

.assignments-table th {
    background-color: var(--background-light);
    font-weight: 600;
}

.invigilators-list {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.invigilator-name {
    padding: 2px 6px;
    background: var(--background-light);
    border-radius: 4px;
    font-size: 11px;
}

.status-good {
    color: var(--success-green);
    font-weight: 500;
}

.status-neutral {
    color: var(--text-secondary);
}

.status-warning {
    color: var(--warning-orange);
    font-weight: 500;
}

.status-unknown {
    color: var(--text-secondary);
    font-style: italic;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-secondary);
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 20px;
}

.empty-state h3 {
    color: var(--text-primary);
    margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .principles-grid {
        grid-template-columns: 1fr;
    }

    .assignments-table {
        font-size: 10px;
    }

    .assignments-table th,
    .assignments-table td {
        padding: 4px;
    }
}
</style>

<script>
// 页面加载动画
document.addEventListener('DOMContentLoaded', function() {
    const sections = document.querySelectorAll('.session-section');

    sections.forEach((section, index) => {
        section.style.opacity = '0';
        section.style.transform = 'translateY(20px)';

        setTimeout(() => {
            section.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            section.style.opacity = '1';
            section.style.transform = 'translateY(0)';
        }, index * 200);
    });
});

// 表格行高亮
document.addEventListener('DOMContentLoaded', function() {
    const tableRows = document.querySelectorAll('.assignments-table tbody tr');

    tableRows.forEach(row => {
        row.addEventListener('mouseenter', function() {
            this.style.backgroundColor = 'rgba(22, 119, 255, 0.05)';
        });

        row.addEventListener('mouseleave', function() {
            this.style.backgroundColor = '';
        });
    });
});
</script>

<?php
// 关闭数据库连接
if (isset($conn)) {
    $conn->close();
}

require 'common/footer.php';
?>